import { Scan } from '@nutui/icons-react-taro';
import {
  Button,
  Loading,
  Overlay,
  Popup,
  SearchBar,
} from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useRequest } from 'ahooks';
import { useState } from 'react';
import CommonTitle from '../../../components/CommonTitle';
import { queryBatteryStatusApi } from '../../../servers/servers';
import { BatteryOperatingStates, BatteryStatusEnum } from './common';
import './index.less';

const jiebangdianchi = () => {
  const {
    runAsync,
    data: batteryList,
    loading,
  } = useRequest(
    async (battery) => {
      if (!battery) {
        return [];
      }
      // 至少输入5个字符
      if (battery?.length < 6) {
        Taro.showToast({
          title: '请最少输入6位电池编码',
          icon: 'none',
          duration: 5000,
        });

        // return [];
      }

      const _res = await queryBatteryStatusApi({
        id: battery,
      });

      return _res?.data;
    },
    {
      debounceWait: 300,
      manual: true,
    },
  );

  const [searchValue, setSearchValue] = useState('');

  /* 当前被查看定位的用户 */
  const [viweUser, setViweUser] = useState('');

  const [open, setOpen] = useState(false);

  // 经纬度
  const [location, setLocation] = useState([]);

  const [batteryInfo, setbatteryInfo] = useState({});

  const WrapperStyle = {
    display: 'flex',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  };

  const columns = [
    {
      title: '电池',
      key: 'batteryId',
      fixed: 'left',
      width: 220,
    },
    {
      title: '在线状态',
      key: 'onlineStatus',
      render: (text, onlineStatus) => {
        return <div>{BatteryStatusEnum[onlineStatus]}</div>;
      },
    },
    {
      title: '剩余电量',
      key: 'currentCapacity',
    },
    // {
    //   title: "运营子状态",
    //   key: "name",
    //   render: (text, operatingSubState) => {
    //     return <div>{BatteryOperatingStates[operatingSubState]}</div>;
    //   },
    // },
    {
      title: '运营子状态',
      key: 'operatingSubState',
      render: (text, operatingSubState) => {
        console.log('text.operatingSubState', text.operatingSubState);
        return <div>{BatteryOperatingStates[text.operatingSubState]}</div>;
      },
    },
    {
      title: '所属组织名称',
      key: 'orgName',
      render: (data, orgName) => {
        // 如果是
        if (+data.operatingSubState === 23) {
          return <div>{data.orgName}</div>;
        }

        return '-';
      },
    },
    {
      title: '绑定人电话',
      key: 'bindUserPhone',
      render: (data, bindUserPhone) => {
        // 如果是用户绑定
        if (+data.operatingSubState === 22) {
          return <div>{data.bindUserPhone}</div>;
        }

        return '-';
      },
    },
    {
      title: '电柜编码',
      key: 'lastBindCabinet',
      render: (data, bindUserPhone) => {
        // 如果在柜
        if (+data.operatingSubState === 21) {
          return <div>{data.lastBindCabinet}</div>;
        }

        return '-';
      },
    },
    {
      title: '仓门号',
      key: 'lastCabinNo',
      render: (data, bindUserPhone) => {
        // 如果在柜
        if (+data.operatingSubState === 21) {
          return <div>{data.lastCabinNo}</div>;
        }

        return '-';
      },
    },
    {
      title: '定位查询',
      key: 'na121212me',
      render: (_record, index) => {
        return (
          <Button
            onClick={async () => {
              setOpen(true);
              setViweUser(_record?.name);
              setLocation([
                _record?.batteryLongitude,
                _record?.batteryLatitude,
              ]);

              setbatteryInfo({
                batteryId: _record?.batteryId,
                batteryLongitude: _record?.batteryLongitude,
                batteryLatitude: _record?.batteryLatitude,
                updateTime: _record?.updateTime,
              });
            }}
          >
            查询定位
          </Button>
        );
      },
    },
  ];

  return (
    <div className="batterystatus_box">
      <Overlay visible={loading}>
        <div className="wrapper" style={WrapperStyle}>
          <Loading direction="vertical">加载中...</Loading>
        </div>
      </Overlay>

      <SearchBar
        autoFocus
        style={{
          '--nutui-searchbar-input-height': '100rpx',
        }}
        onChange={(_val) => {
          setSearchValue(_val);
        }}
        value={searchValue}
        left={
          <Scan
            onClick={() => {
              // 允许从相机和相册扫码
              Taro.scanCode({
                scanType: 'qrCode',
                success: (res) => {
                  const pattern = /BT.*$/;

                  const match = res?.result?.match(pattern);
                  if (match) {
                    setSearchValue(match?.[0]);
                  } else {
                    Taro.showToast({
                      title: '请扫描正确的二维码',
                      icon: 'none',
                      duration: 2000,
                    });
                  }

                  console.log(res);
                },
                errMsg: (_res) => {
                  console.log(_res);
                },
              });
            }}
          />
        }
        placeholder="输入电池编码后6位进行搜索"
        right={
          <Button
            type="primary"
            onClick={() => {
              runAsync(searchValue);
            }}
          >
            搜索
          </Button>
        }
        onSearch={(vales) => {
          runAsync(vales);
        }}
      />

      {batteryList &&
        batteryList?.length > 0 &&
        batteryList?.map((_item) => {
          return (
            <div
              key={_item?.batteryId + _item?.provinceId}
              className="batterystatus_box_card_item"
            >
              <View className="at-article__p">
                电池编号：{_item?.batteryId ?? '-'}
              </View>

              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <View className="at-article__p">
                  电池状态：{BatteryStatusEnum[_item?.onlineStatus]}
                </View>

                <View className="at-article__p">
                  剩余电量：{_item?.currentCapacity}%
                </View>

                <View className="at-article__p">
                  运营子状态：{BatteryOperatingStates[_item?.operatingSubState]}
                </View>
              </div>

              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  paddingRight: '30rpx',
                }}
              >
                <View className="at-article__p">
                  所在渠道：{_item?.optName || _item?.orgName || _item?.orgName || _item?.enterpriseName}
                </View>
                {/* data.bindUserPhone */}
                <View className="at-article__p">
                  绑定人：{_item?.bindUserPhone ? _item?.bindUserPhone : '-'}
                </View>
              </div>

              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  paddingRight: '30rpx',
                }}
              >
                <View className="at-article__p">
                  所在柜：
                  {_item?.lastCabinetId ? _item?.lastCabinetId : '-'}
                </View>

                <View className="at-article__p">
                  所在仓：{_item?.lastBindCabin ? _item?.lastBindCabin : '-'}
                </View>
              </div>

              <Button
                style={{
                  width: '90%',
                  marginLeft: '5%',
                  marginTop: 30,
                }}
                block
                type="primary"
                onClick={() => {
                  setOpen(true);
                  setViweUser(_item?.name);
                  setLocation([
                    _item?.batteryLongitude,
                    _item?.batteryLatitude,
                  ]);

                  setbatteryInfo({
                    batteryId: _item?.batteryId,
                    batteryLongitude: _item?.batteryLongitude,
                    batteryLatitude: _item?.batteryLatitude,
                    updateTime: _item?.updateTime,
                  });
                }}
              >
                定位查询
              </Button>
            </div>
          );
        })}

      {/* <Table columns={columns} data={batteryList} /> */}

      <Popup
        destroyOnClose
        visible={open}
        position="bottom"
        style={{ height: '260rpx' }}
        onClose={() => {
          setOpen(false);
        }}
      >
        <view>
          <View
            className="at-article__h3"
            style={{
              paddingTop: 10,
              paddingBottom: 10,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            {batteryInfo?.batteryId}
            <Button
              type="primary"
              onClick={() => {
                Taro.openLocation({
                  latitude: Number(location?.[1]),
                  longitude: Number(location?.[0]),
                  scale: 18,
                });
              }}
            >
              导航
            </Button>
          </View>
          <CommonTitle title="电池定位信息" />
          <div
            style={{
              display: 'flex',
            }}
          >
            <View className="at-article__p">经度：{location?.[0]}</View>
            <View className="at-article__p">纬度：{location?.[1]}</View>
          </div>
          {/* <View className="at-article__p">用户姓名：{viweUser}</View> */}
          <View className="at-article__p">
            更新时间：{batteryInfo?.updateTime}
          </View>
        </view>
      </Popup>
    </div>
  );
};

export default jiebangdianchi;
